#!/usr/bin/env python
#encoding=utf-8
import MySQLdb
from  optparse import OptionParser
import sys
import time
import os
reload(sys)
sys.setdefaultencoding("utf8")
MY_CONFIG={"host":"10.9.35.226","user":"test","db":"loadtest","passwd":"test@123","charset":"utf8"}



def main():
	try:
		parser=OptionParser()
		parser.add_option("-H","--host",dest="host",help="domain_port eg.10.10.78.89:8001")
		parser.add_option("-a","--AppName",dest="app",help="webapp_name eg.shark ")
		parser.add_option("-s","--StartDateTime",dest="start_datetime",help="start_Datetime yyyymmddHHMMSS eg.20160102213059")
		parser.add_option("-e","--EndDataTime",dest="end_datetime",help="end_Datetime yyyymmddHHMMSS eg.20161228")
		parser.add_option("-t","--TransactionName",dest="transaction",help="transaction_name, eg.power-update ")
		parser.add_option("-m","--MaxRequests",dest="limit",help="max_requests_size eg.900000")
	except Exception,e:
		print e
	else:

		(a,b)=parser.parse_args()
		
		c,d=__getSQL(eval(a.__str__()))
		__pullDB2fs(c,d)
		
		
		
		
def __getSQL(kw):
	condition = list()
	sql="select request_uri ,request_data from loadtest.requests  %s  order by create_datetime ASC "
	tmp_sql=""
	
	for k ,v in kw.items():
		if v is None:
			del kw[k]
	if kw.has_key("start_datetime"):
		condition.append("create_datetime >= %s" % int(time.mktime(time.strptime(kw.pop("start_datetime").ljust(14,"0"),"%Y%m%d%H%M%S"))))
	if kw.has_key("end_datetime"):
		condition.append("create_datetime <= %s" % int(time.mktime(time.strptime(kw.pop("end_datetime").ljust(14,"0"),"%Y%m%d%H%M%S"))))
	if kw.has_key("app"):

		condition.append("app = '%s' " % kw.pop("app"))
	if kw.has_key("transaction"):

		condition.append("transaction = '%s' " % kw.pop("transaction"))
	if len(condition)>0:
		tmp_sql=" and ".join(condition)
		tmp_sql=" where "+ tmp_sql
	if kw.has_key("limit"):
		sql+=" limit %s" % kw.pop("limit")
	return  sql % tmp_sql ,kw.pop("host",None)

	
def __pullDB2fs(sql,host=None):
	cur=None
	try:
		
		print sql
		cur=MySQLdb.connect(**MY_CONFIG).cursor(cursorclass=MySQLdb.cursors.DictCursor)
		result = cur.execute(sql)
		if result:
			fh=file("/tmp/request.data.%d" % int(result),"w+")
			fh.write("host=%s%s" % (host,os.linesep))
			for i in cur:
				if i["request_data"]=="":
					fh.write("$(host)%s%s" % (i["request_uri"],os.linesep))
				else:
					fh.write("$(host)%s POST %s%s" % (i["request_uri"],i["request_data"],os.linesep))
			fh.flush()
			fh.close()
			cur.close()
			print("新增文件%s" % fh.name)
		else:
			print("没有符合条件的数据，请重新设置检索条件")

	except MySQLdb.Error,e:
		print e
	except IOError,e:
		print e
	finally:
		if cur is not None:
			cur.close()
		


	

if __name__=="__main__":
	if len(sys.argv)>1:

		main()
	else:
		sys.exit()

